<template>
  <div>

    <!-- 居中容器 -->
    <div class="container">

      <!-- 页头 -->
      <div class="page-header">
        <h1>我的购物车 <small>快来把我带回家吧!</small></h1>
      </div>

      <!-- 购物车 -->
      <ul v-if="cart.items.length > 0" class="list-group">
        <li class="list-group-item" v-for="(item, index) in cart.items">

          <!-- 复选框 -->
          <label class="cart-checkbox" @click="select($event, index)">
            <input type="checkbox" :checked="item.selected">
          </label>

          <!-- 图片 -->
          <img :src="parseImage(item.commodity.image)" :alt="item.name" class="img-thumbnail">

          <!-- 购物车子项信息 -->
          <div class="cart-info">
            <div>
              <h3>{{item.commodity.name}}</h3>
              <h4>¥{{item.commodity.price}}.00</h4>
              <p><span class="label label-info">简介</span> {{item.commodity.description}}</p>
              <p><span class="label label-success">库存</span> 剩余 {{item.commodity.storage}} 件</p>
            </div>
          </div>

          <!-- 购物车子项控制 -->
          <div class="cart-control">
            <button class="btn btn-default" style="margin-right: 10px;" data-loading-text="..." @click="remove($event, index)"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
            <button class="btn btn-default" data-loading-text="..." @click="decrease($event, index)"><span class="glyphicon glyphicon-minus" aria-hidden="true"></span></button>
            <span class="cart-control-amount">{{item.amount}}</span>
            <button class="btn btn-primary" data-loading-text="..." @click="increase($event, index)"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></button>
          </div>

        </li>
      </ul>

      <!-- 没有商品时显示 404 图片 -->
      <div v-else style="text-align: center;">
        <img src="../assets/bitmap_404.png" height="300">
        <h2 style="margin: 50px auto 100px auto;">你的购物车空空如也噢!</h2>
      </div>
    </div>

    <!-- 底部购买导航条 -->
    <nav class="navbar navbar-default navbar-fixed-bottom">
      <div class="container-fluid">

        <div class="navbar-header">
          <div class="checkbox navbar-text">
            <label><input type="checkbox" :checked="isAllSelect" v-model="isAllSelect"> 全选</label>
<!--            <button class="btn btn-default" style="margin-left: 20px;" data-loading-text="..." @click="remove($event, -1)"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>-->
          </div>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse">
          <div class="navbar-form navbar-right">
            <div class="form-group">
              <p class="nav navbar-nav">
                <strong>合计: </strong>
                <span class="cart-sum">¥ {{this.cart.totalPrice}}.00</span>
              </p>
            </div>
            <button id="btn-search" type="submit" class="btn btn-primary" @click="purchase" data-loading-text="结算中...">
              <span class="glyphicon glyphicon-credit-card" aria-hidden="true"></span>
              结算
            </button>
          </div>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>

  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "CartPage",
  data() {
    return {
      // isAllSelect: false,
      // cart: {
      //   id: 0,
      //   items: [],
      //   totalPrice: 0.0
      // }
    }
  },
  computed: {
    isAllSelect: {
      get: function () {
        console.log('isAllSelect...')
        if (this.cart.items.length <= 0) return false
        return this.cart.items.every((item) => {
          return item.selected
        })
      },
      set: function (val) {
        this.post('select', {
          cartId: this.cart.id,
          itemId: -1,
          selected: val
        })
      }
    },
    cart: {
      get: function () {
        return this.$store.state.cart
      },
      set: function (val) {
        this.$store.commit('updateCart', val)
      }
    }
  },
  methods: {

    // 选择商品
    select: function (event, index) {
      if (index >= this.cart.items.length) return
      let item = this.cart.items[index]
      console.log('selecting...' + index + ' -> ' + !item.selected)
      this.post('select', {
        cartId: this.cart.id,
        itemId: item.id,
        selected: !item.selected
      })
    },

    // 添加数量
    increase: function(event, index) {
      if (index >= this.cart.items.length) return
      let item = this.cart.items[index]
      this.post('increase', {
        cartId: this.cart.id,
        itemId: item.id,
      })
    },

    // 减少数量
    decrease: function(event, index) {
      if (index >= this.cart.items.length) return
      let item = this.cart.items[index]
      this.post('decrease', {
        cartId: this.cart.id,
        itemId: item.id,
      })
    },

    remove: function(event, index) {
      if (index >= this.cart.items.length) return
      let item = this.cart.items[index]
      this.post('remove', {
        cartId: this.cart.id,
        itemId: item.id,
      })
    },

    purchase: function() {
      this.$axios.post(
        '/order/purchase',
        this.$qs.stringify({
          userId: this.$store.state.user.id
        })
      ).then((res) => {
        console.log('[./order/purchase] 获取成功...')
        console.log(res.data)
        this.$store.state.orders.push(res.data)
        this.$store.state.order_id = res.data.id;
        this.$store.state.order_index = this.$store.state.orders.length - 1;
        this.$router.push({name:'orderDetail'})
      }).catch(function (error) {
        console.log('/order/purchase 获取失败...')
        console.log(error)
      })
    },

    // post 模板
    post: function (url, data) {

      /* 判断当前用户是否已登录 */
      if (this.cart.id <= 0) {
        alert("请先登录！")
        return
      }

      this.$axios.post(
        '/cart/' + url,
        this.$qs.stringify(data)
      ).then((res) => {
        console.log('/cart/' + url + ' 获取成功...')
        console.log(res.data)
        this.cart = res.data
      }).catch(function (error) {
        console.log('/cart/increase 获取失败...')
        console.log(error)
      })
    },

    // 图片路径解析
    parseImage: function (name) {
      return axios.defaults.baseURL + '/images/' + name + '.png'
    }
  },
  beforeMount() {
    console.log('CartPage beforeMount...')
    let user = this.$store.state.user
    if (user == null) return
    this.$axios.post(
      '/cart/instance',
      this.$qs.stringify({ userId: user.id })
    ).then((res) => {
      console.log('获取成功...')
      console.log(res.data)
      this.cart = res.data
    }).catch(function (error) {
      console.log('获取失败...')
      console.log(error)
    })
  }
}
</script>

<style scoped>
.list-group {
  margin-bottom: 100px;
}

.list-group-item .cart-checkbox {
  margin-left: 10px;
  margin-right: 20px;
}

.list-group-item .img-thumbnail {
  width: 200px;
  height: 200px;
  object-fit: cover;
}

.cart-info h4{
  margin-left: 20px;
  font-weight: 600;
  color: rgba(100, 100, 255, 1);
}

.cart-info p{
  color: #555;
  margin-left: 10px;
}

.cart-info {
  display: inline-flex;
  position: relative;
  left: 24px;
  top: -64px;
// background-color: lightcoral;
}

.cart-control {
  float: right;
  position: relative;
  right: 10px;
  bottom: -160px;
// background-color: lightcoral;
}

.cart-control .cart-control-amount {
  font-weight: 600;
  margin: auto 20px;
}

.cart-sum{
  margin-left: 10px;
  margin-right: 20px;
  font-size: 18px;
  color: rgb(100, 100, 100);
}

.navbar{
  width: 60%;
  margin: auto;
  border-radius: 10px;
}

.navbar-collapse {
  margin-top: 5px;
}
</style>
